package com.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GuliFeignConfig
 * @Author 徐涛
 * @Date 2020/11/11 16:40
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();//之前的请求
                    //  System.out.println("feign远程方法之前先进行RequestInterceptor.apply");
                    if (request != null) {
                        
                        //同步请求头数据，cookie
                        String cookie = request.getHeader("cookie");
                        //给新请求同步了老请求的cookie
                        requestTemplate.header("cookie", cookie);
                    }
                }
            }
        };
    }

}
